//
//  TACP_BaseModel.m
//  AutoCreatePropertyDemo
//
// Created by userName on 2017/11/30.
//  Copyright © 2017年 __MyCompanyName__ All rights reserved.
//

#import <objc/runtime.h>
#import "TACP_BaseModel.h"

//请不要改动此方法
id _Nullable not_null_obj_from_dict_with_key(NSDictionary * _Nonnull dict, id _Nonnull aKey) {
    id obj = dict[aKey];
    if ([obj isKindOfClass:[NSNull class]]) {
        obj = nil;
    }
    return obj;
}

//请不要改动此方法
//num 不存在时返回0
NSInteger int_value_from_num(NSNumber *num) {
    if (!num) return 0;
    return num.integerValue;
}

//请不要改动此方法
//num 不存在时返回0
BOOL bool_value_from_num(NSNumber *num) {
    if (!num) return 0;
    return num.boolValue;
}

//请不要改动此方法
//num 不存在时返回0
double double_value_from_num(NSNumber *num) {
    if (!num) return 0;
    return num.doubleValue;
}

@implementation TACP_BaseModel

- (instancetype)initWithDictionary:(NSDictionary *)dict {
    self = [super init];
    if (self) {
    
    }
    return self;
}

- (NSArray *)arrayFromDatasource:(NSArray *)array subClassName:(NSString *)subClassName {
    NSMutableArray *marr  = [NSMutableArray new];
    for (id obj in array) {
        if ([obj isKindOfClass:[NSArray class]]) {
            [marr addObject:[self arrayFromDatasource:obj subClassName:subClassName]];
        } else if ([obj isKindOfClass:[NSDictionary class]]) {
            if (!subClassName.length) {
                continue;
            }
            Class aClass = NSClassFromString(subClassName);
            id model = [[aClass alloc] initWithDictionary:obj];
            [marr addObject:model];
        } else {
            [marr addObject:obj];
        }
    }
    return marr;
}

- (void)encodeWithCoder:(NSCoder *)encoder
{
    unsigned int count = 0;
    //  利用runtime获取实例变量的列表
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i ++) {
        //  取出i位置对应的实例变量
        Ivar ivar = ivars[i];
        //  查看实例变量的名字
        const char *name = ivar_getName(ivar);
        //  C语言字符串转化为NSString
        NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        //  利用KVC取出属性对应的值
        id value = [self valueForKey:nameStr];
        //  归档
        [encoder encodeObject:value forKey:nameStr];
    }
    
    //  记住C语言中copy出来的要进行释放
    free(ivars);
    
}

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i ++) {
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            
            //
            NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
            id value = [decoder decodeObjectForKey:key];
            //  设置到成员变量身上
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    return self;
}


@end
